简体   繁体   中英

How to add a string to every line in a file with Bash

I have a file ( myfile.txt ) that contains these lines:

foo
bar
qux

In a bash script I'd like to add a value on the string resulting in

foo 1000
bar 1000
qux 1000

I tried this but failed.

#!/usr/bin/bash
MYVAL="1000"
cat myfile.txt | xargs -I '{}' echo {} & echo $MYVAL

which only prints 1000 on one line.

You can use sed and you don't really need a pipe for this:

myval="1000"
sed "s/$/ $myval/" file > file.modified

for in-place editing:

sed -i "s/$/ $myval/" file
  • s/$/ $myval/ - places a space followed by the value of $myval at the end of each line

More about sed here: http://grymoire.com/Unix/Sed.html

Your attempt is almost there:

$ xargs -I{} echo {} 1000 < file6
boo djhg 1000
bio jdjjf 1000
dgdhd bgo 1000
ghhh 1000
baao biologico bata 1000
baa beto biologic 1000
bojo bija 1000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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