簡體   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