SED Guru Needed -- Combine Two SED Commands Into One Liner
I am trying to do in-place editing of each line that begins with the letter D, keeping the last 3 characters appended to the first 15 characters. I found separate sed commands to do the separate functions but cannot figure out how to combine them into a single command line:
# To remove everything except the 1st n characters in every line: Code:
sed -r 's/(.{15}).*/\1/' file Code:
sed -r 's/.*(.{3})/\1/' file Code:
D some text end Code:
D some text end Thanks!!! |
There are probably several ways to combine the two. If I understand the way you've described it, then one way would be like this:
Code:
sed -r -e '/^D/s/^(.{15}).*(.{3})$/\1\2/' Do you want it to suppress printing of lines that start without a D? The above lets them pass through unmodified. |
Hi Turbocapitalist. Thanks for the speedy reply!! Thats not working for me. Its not appending the last 3 characters. I am using grep to test the sed command:
Code:
grep ^D file |sed -r -e '/^D/s/^(.{15}).*(.{3})$/\1\2/' |
Oh!! This is working!!
Code:
grep ^D file |sed -r -e 's/^D(.{15}).*.*(.{3})$/\1\2/' |
No worries, but the grep is unneeded and probably in the way. The /D/ takes the place of grep and applies the substitution only matching lines. Try like mentioned above
Code:
sed -r -e '/^D/s/^(.{15}).*(.{3})$/\1\2/' somefile If you want to eliminate lines that don't start with 'D' then you can throw in a conditional branch (t) to hop over a delete command (d) : Code:
sed -r -e '/^D/s/^(.{15}).*(.{3})$/\1\2/;t;d;' somefile Code:
man sed |
All times are GMT -5. The time now is 07:30 AM. |