Linux 在 Bash 中,如何在文件中的每一行后添加一个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2869669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Bash, how do I add a string after each line in a file?
提问by Jason Volkoz
How do I add a string after each line in a file using bash? Can it be done using the sed command, if so how?
如何使用 bash 在文件中的每一行后添加一个字符串?可以使用 sed 命令完成吗,如果可以,怎么做?
采纳答案by Tom DeGisi
If your sedallows in place editing via the -iparameter:
如果您sed允许通过-i参数进行就地编辑:
sed -e 's/$/string after each line/' -i filename
If not, you have to make a temporary file:
如果没有,您必须制作一个临时文件:
typeset TMP_FILE=$( mktemp )
touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename
回答by hendry
Sed is a little ugly, you could do it elegantly like so:
Sed 有点难看,你可以像这样优雅地做到:
hendry@i7 tmp$ cat foo
bar
candy
car
hendry@i7 tmp$ for i in `cat foo`; do echo ${i}bar; done
barbar
candybar
carbar
回答by martin clayton
回答by Optimus Prime
I prefer using awk.
If there is only one column, use $0, else replace it with the last column.
我更喜欢使用awk. 如果只有一列,请使用$0,否则将其替换为最后一列。
One way,
单程,
awk '{print awk 'suffix=foobar
while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file |
sponge file
=suffix=foobar
xargs -L 1 printf "%s${suffix}\n" < file | sponge file
"string to append after each line"' file > new_file
, "string to append after each line"}' file > new_file
or this,
或这个,
suffix=foobar
join file file -e "${suffix}" -o 1.1,2.99999 | sponge file
回答by agc
Pure POSIX shelland
sponge:suffix=foobar paste file <(yes "${suffix}" | head -$(wc -l < file) ) | sponge filexargsandprintf:suffix=foobar while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file | sponge fileUsing
join:suffix=foobar xargs -L 1 printf "%s${suffix}\n" < file | sponge fileShell tools using
paste,yes,head&wc:suffix=foobar join file file -e "${suffix}" -o 1.1,2.99999 | sponge fileNote that
pasteinserts a Tabchar before$suffix.
纯POSIX 外壳和
sponge:suffix=foobar paste file <(yes "${suffix}" | head -$(wc -l < file) ) | sponge filexargs和printf:cat file | while read line; do echo ${line}$string; done使用
##代码##join:使用
##代码##paste,yes,head& 的Shell 工具wc:请注意,在 之前
paste插入一个Tab字符$suffix。
Of course spongecan be replaced with a temp file, afterwards mv'd over the original filename, as with some other answers...
当然sponge可以用临时文件替换,然后替换mv原始文件名,就像其他一些答案一样......
回答by 欢乐的Xiaox
I prefer echo. using pure bash:
我更喜欢echo。使用纯 bash:

