0

Say I have a file named output.txt. Every line in output.txt starts with a different word. How could I perform something like if any line starts with "word" then add "new word" to the end of the line?

4 Answers 4

2

Here's one way using Perl.

perl -p -e'$_ .= "new word" if /^word/" output.txt > newfile.txt

If you want to edit the file in place you would use Perl's -i flag for "in place edit"

perl -i -p -e'$_ .= "new word" if /^word/" output.txt

You could also use sed or awk.

Sign up to request clarification or add additional context in comments.

Comments

2

Andy's answer is good. If you want to use sed you could do

sed 's/\(^word.*$\)/\1new word/' input.txt > output.txt

1 Comment

Even simpler: sed '/^word/s/$/new word/' input.txt > output.txt. This "replaces" the end of the line with "new word", but only on lines that begin with "word".
1
while read i; do
    if [[ $i == word* ]]; then
        echo ${i}newword >> newfile
    else
        echo $i >> newfile
    fi
done < "file.txt"

Comments

0

awk:

awk '$1 == "word" {$(NF+1) = "new word"} 1' output.txt > tempfile &&
mv tempfile output.txt

I'm assume you don't necessarily need regex matching for the first word

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.