Combine multiple sed commands into one

Viewed 141

I have a file example.txt, I want to delete and replace fields in it.

The following commands are good, but in a very messy way, unfortunately I'm a rookie to sed command.

The commands I used:

sed 's/\-I\.\.\/\.\.\/\.\.//\n/g' example.txt > example.txt1

sed 's/\-I/\n/g' example.txt1 > example.txt2

sed '/^[[:space:]]*$/d' > example.txt2 example.txt3

sed 's/\.\.\/\.\.\/\.\.//g' > example.txt3 example.txt

and then I'm deleting all the unnecessary files.

I'm trying to get the following result:

Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App

The file looks like this:

-I../../../Common/Component -I../../../Common/Component1 -I../../../Common/Component2 -I../../../Common/Component3 -I../../../Common/Component4 -I../../../Common/Component5 -I../../../Common/Component6 -IComp  -IApp  ../../../ 

I want to know how the best way to transform input format to output format standard text-processing tool with 1 call with sed tool or awk.

4 Answers

If you don't REALLY want the string /Components to be added in the middle of some output lines then this may be what you want, using any awk in any shell on every Unix box:

$ awk -v RS=' ' 'sub("^-I[./]*","")' file
Common/Component
Common/Component1
Common/Component2
Common/Component3
Common/Component4
Common/Component5
Common/Component6
Comp
App

That would fail if any of the paths in your input contained blanks but you don't show that as a possibility in your question so I assume it can't happen.

With your shown samples, please try following awk code. Written and tested in GNU awk.

awk -v RS='-I\\S+' 'RT{sub(/^-I.*Common\//,"Common/Components/",RT);sub(/^-I/,"",RT);print RT}' Input_file

output with samples will be as follows:

Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App

Explanation: Simple explanation would be, in GNU awk. Setting RS(record separator) as -I\\S+ -I till a space comes. In main awk program, check if RT is NOT NULL, substitute starting -I till Common with Common/Components/ in RT and then substitute starting -I with NULL in RT. Then printing RT here.

What about

sed -i 's/\-I\.\.\/\.\.\/\.\.//\n/g
s/\-I/\n/g
/^[[:space:]]*$/d
s/\.\.\/\.\.\/\.\.//g' example.txt

Using sed

$ sed 's|\([A-Z][^/]*/\)\([A-Z][^0-9 ]*\)|\1\2s/\2|g;s/-I/\n/g;s/\.[^[:alnum:]]*//g' input_file

Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App
Related