繁体   English   中英

在 Bash 中,如何在文件的每一行之后添加一个字符串?

[英]In Bash, how do I add a string after each line in a file?

如何使用 bash 在文件中的每一行之后添加一个字符串? 可以使用 sed 命令完成吗,如果可以,怎么做?

如果您的sed允许通过-i参数进行就地编辑:

sed -e 's/$/string after each line/' -i filename

如果没有,您必须制作一个临时文件:

typeset TMP_FILE=$( mktemp )

touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename

我更喜欢使用awk 如果只有一列,请使用$0 ,否则将其替换为最后一列。

单程,

awk '{print $0, "string to append after each line"}' file > new_file

或这个,

awk '$0=$0"string to append after each line"' file > new_file

我更喜欢echo 使用纯 bash:

cat file | while read line; do echo ${line}$string; done

如果你有它, lam (层压)实用程序可以做到这一点,例如:

$ lam filename -s "string after each line"
  1. POSIX 外壳sponge

     suffix=foobar while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file | sponge file
  2. xargsprintf

     suffix=foobar xargs -L 1 printf "%s${suffix}\n" < file | sponge file
  3. 使用join

     suffix=foobar join file file -e "${suffix}" -o 1.1,2.99999 | sponge file
  4. 使用paste的 Shell 工具, yes的, head & wc

     suffix=foobar paste file <(yes "${suffix}" | head -$(wc -l < file) ) | sponge file

    请注意, paste$suffix之前插入一个Tab字符。

当然, sponge可以用临时文件替换,然后mv覆盖原始文件名,就像其他一些答案一样......

这只是添加使用 echo 命令在文件中每一行的末尾添加一个字符串:

cat input-file | while read line; do echo ${line}"string to add" >> output-file; done

添加>>指示我们对输出文件所做的更改。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM