Issue
Can I avoid duplicate strings with the sed "a" command?
I added the word "apple" under "true" in my file.txt.
The problem is that every time I run the command "apple" is appended.
$ sed -i '/true/a\apple' file.txt ...execute 3 time
$ cat file.txt
true
apple
apple
apple
If the word "apple" already exists, repeating the sed command does not want to add any more.
I have no idea, please help me
...
I want to do this,
...execute sed command anytime
$ cat file.txt
true
apple
Solution
It seems you don't want to append the line apple
if the line following the true
already contains apple
. Then this sed
command should do the trick.
sed -i.backup '
/true/!b
$!{N;/\napple$/!s/\n/&apple&/;p;d;}
a\
apple
' file.txt
Explanation of sed
commands:
- If the line doesn't contain true then jump to the end of the script, which will print out the line read (
/true/!b
).
Otherwise the line contains true:
- If it isn't the last line (
$!
) then
• read the next line (N
).
• If the next line doesn't consist of apple (/\napple$/!
) then insert the apple between two lines (s/\n/&apple&/
).
• Print out the pattern space (p
) and start a new cycle (d
)
Otherwise it is the last line (and contains true)
- Append apple (
a\ apple
)
Edit:
The above sed
script won't work properly if two consecutive true line occurs in the file, as pointed out by @potong. The version below should fix this, if I haven't overlooked something.
sed -i.backup ':a
/true/!b
a\
apple
n
/^apple$/d
ba
' file.txt
Explanation:
/true/!b
: If the line doesn't contain true, no further processing is required. Jump to the end of the script. This will print the current pattern space.a\ apple
: Otherwise, the line containstrue
. Append apple.n
: Print the current pattern space and appended line (apple) and replace the pattern space with the next line. This will end the script if no next line available./^apple$/d
: If the line read consists of string apple then delete it and start a new cycle (because it is already appended before)ba
: Jump to the start of the script (labela
) without reading an input line.
Answered By - M. Nejat Aydin Answer Checked By - Terry (WPSolving Volunteer)