一、Shell写文件内容
在Shell中,可以使用echo将内容输出到终端。如果需要将内容输出到文件中,可以将echo和重定向符号“>”组合使用,将内容输出到文件中。如下所示:
echo "Hello World!" > test.txt
上述代码将字符串“Hello World!”写入test.txt文件中。如果需要将多行内容写入同一文件,可以使用echo和追加重定向符号“>>”。
echo "first line" > test.txt echo "second line" >> test.txt echo "third line" >> test.txt
上述代码首先将字符串“first line”写入test.txt文件中,然后使用追加符号“>>”将“second line”和“third line”分别附加到文件末尾。
二、Shell写文件换行
在Shell中,可以使用echo命令结合转义符“\n”实现写文件时的换行。如下所示:
echo -e "first line\nsecond line" > test.txt
上述代码中,使用-e选项开启了转义符的解析功能,字符串中的“\n”会被解释成换行符。
三、Shell写文件指定字符集
在Shell中,可以使用iconv命令进行字符集转换,以在写文件时指定字符集。如下所示:
echo "中文" | iconv -f utf8 -t gb2312 > test.txt
上述代码将utf8字符集的“中文”转换为gb2312字符集并写入test.txt文件中。
四、Shell写文件命令
在Shell中,除了echo和重定向符号“>”之外,还可以使用cat命令将文件内容写入指定文件。如下所示:
cat > test.txt This is a test document Ctrl+d
上述代码使用cat命令输出一行“This is a test document”到终端,Ctrl+d表示结束输入。cat将终端上的输入重定向到test.txt文件中。
五、Shell写文件左对齐
使用printf命令可以控制输出的格式,进而实现左对齐等效果。如下所示:
printf "%-10s %-10s %-10s\n" "Name" "Age" "Gender" > test.txt
上述代码使用printf格式化输出三列表头信息,并将其左对齐后写入test.txt文件中。%-10s表示左对齐,占用10个字符的位置。
六、Shell写文件保留空格
默认情况下,echo会忽略字符串中的多余空格。如果需要保留空格,可以使用引号将字符串括起来,或者使用printf命令。如下所示:
echo " This is a test" > test.txt printf " %s\n" "This is a test" > test.txt
上述代码中,第一行使用echo忽略多余空格,第二行使用printf命令将空格保留,并写入test.txt文件中。
七、Shell写文件 gb2312
如果需要将数据以gb2312编码写入文件,可以使用iconv命令进行字符集转换。如下所示:
echo "中文" | iconv -f utf8 -t gb2312 > test.txt
上述代码将utf8字符集的“中文”转换为gb2312字符集并写入test.txt文件中。
八、Shell写文件到csv不同表
使用printf命令将数据格式化为csv文件的不同表部分。如下所示:
printf "%-10s,%-10s,%-10s\n" "Name" "Age" "Gender" > test.csv printf "%-10s,%-10d,%-10s\n" "John" 25 "Male" >> test.csv printf "%-10s,%-10d,%-10s\n" "Lucy" 27 "Female" >> test.csv
上述代码将姓名、年龄和性别分别格式化为csv文件中的三列,并将两行数据依次写入test.csv文件中。
九、Shell写入内容到文件
除了使用重定向符号和cat命令写文件外,还可以使用tee命令实现将同一串数据同时输出到屏幕和文件中。如下所示:
echo "This is a test" | tee test.txt
上述代码将字符串“This is a test”写入test.txt文件中,并将其在屏幕上输出。
原创文章,作者:EKEQA,如若转载,请注明出处:https://www.506064.com/n/329644.html