2

I have the following text file with the following lines:

<test="123">
<test="456">
<test="789">

My aim is to have the above text file to be appended with a keyword "HELLO" after the above numbers, as following:

  <test="123.HELLO">
  <test="456.HELLO">
  <test="789.HELLO">

with the grep command and cut, I manage to get the value between the quotation mark.

grep -o "test=".* test.txt | cut -d \" -f2

I tried to use sed on top of it, with this line

grep -o "test=".* test.txt | cut -d \" -f2 | sed -i -- 's/$/.HELLO/' test.txt

however the closest I manage to get is instead a ".HELLO" which directly appended on the end of the line (and not after the numbers in between the quotes)

<test="123">.HELLO 
<test="456">.HELLO 
<test="789">.HELLO

How can I fix my sed statement to provide me with the requested line?

1
  • can you clarify: 1) spaces in front of expected output lines is needed or falsely shown here because of formatting 2) does your input file contain lines not containing test=? if so, should they be part of output as well Commented Oct 5, 2016 at 15:53

4 Answers 4

2

You can accomplish this with sed directly. Cut should not be necessary:

grep "test=" test.txt | sed 's/"\(.*\)"/"\1.HELLO"/'
Sign up to request clarification or add additional context in comments.

3 Comments

grep is unnecessary too, as well as -o option should not be used in this case.. and you could add some sample filename to grep command...
Good call, edited my answer. I left the grep in, in case there are extraneous lines in the file that the OA wants left out. Of course it could be done with sed directly, but this seems more simplistic.
fine now :) sed -n '/test=/ s/"\(.*\)"/"\1.HELLO"/p' test.txt is simple too, but I do get your point :)
1

You can do it with groups in sed. To create new output, you can do this:

 sed 's/\(test="[^"]*\)"/\1.HELLO"/g' test.txt

To modify it in-place, you can use the -i switch:

 sed -i 's/\(test="[^"]*\)"/\1.HELLO"/g' test.txt

Explanation:

  • () is a group. You can refer to it with \1. In sed we have to escape the parentheses: \(\)
  • [^"]* matches everything that's not a quote. So the match will stop before the quote
  • In the replacement, you have to add the quote manually, since it's outside of the group. So you can put stuff before the quote.

Comments

1

Try this:

This is how your file looks like.

bash > cat a.txt
<test="123">
<test="456">
<test="789">

Your text piped to SED

bash > cat a.txt |sed 's/">/.HELLO">/g'
<test="123.HELLO">
<test="456.HELLO">
<test="789.HELLO">
bash >

Let me know if this worked out for you.

Comments

1
awk 'sub("[0-9]+","&.HELLO")' file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.