Reputation: 4421
I have a file with this content:
lines
lines
rootdev=UUID=967d8dc3-f595-4a6e-929e-cc89as5a1a2s / ext4 defaults,
lines
I am searching for one line command which should strip everything in the line rootdev
after whitespace, so the final content should be like:
lines
lines
rootdev=UUID=967d8dc3-f595-4a6e-929e-cc89as5a1a2s
lines
Any idea how to do it with one line command? (so I do not need to open nano with this file and do it manually)
I tried with sed
but it just replaces the word rootdev
sed -i 's/rootdev//g' file.txt
Upvotes: 1
Views: 120
Reputation: 50805
First, search for a line beginning with rootdev=
, and when you find it delete everything after the first whitespace until the end of line.
sed -i '/^rootdev=/ s/ .*$//' file
Using a capturing group to keep rootdev=...
part in, and replacing the whole line with it is an option too.
sed -i 's/^\(rootdev=[^ ]*\).*$/\1/' file
Upvotes: 1
Reputation: 85885
Your attempt with sed
can't work because it would just remove rootdev
string with an empty string. What you need is a tool that matches a pattern and does an action on that whole line for which I think awk
is more recommended than sed
.
Using awk
to match the line to strip off the spaces using gsub()
should be sufficient,
awk '/^rootdev/{ gsub(/[[:space:]].*/,"",$0) }1' file
If you are using GNU awk
with version greater than 4.1.0, you could use its in-place edit option to make the changes dynamically
gawk -i inplace '/^rootdev/{ gsub(/[[:space:]].*/,"",$0) }1' file
for earlier versions, use a temporary file
awk '/^rootdev/{ gsub(/[[:space:]].*/,"",$0) }1' file > temp && mv temp file
or use sponge
from moreutils
. If its not available in your system do get it on RHEL using yum install moreutils
or with apt-get
in Debian.
awk '/^rootdev/{ gsub(/[[:space:]].*/,"",$0) }1' file | sponge file
Upvotes: 2