Skip to main content

sed in shell scripts examples

Replace all occurences of 'someText' with 'someOtherText' in someFile​

sed "s/someText/someOtherText/g" -i someFile

Explanation:

  • s/someText/someOtherText replaces 'someText' by 'someOtherText'
  • 'g' after 'someOtherText' stands for 'globally', so all occurences of 'someText' will be replaced by 'someOtherText'
  • with -i flag indicated, the replacements will be made in the file. There is no need to pipe the output to any other binary.

Delete all occurences of 'someText' from someFile​

sed "s/someText//g" -i someFile

So, technically, we replace 'someText' with an empty string.

Replace only the first occurence of 'someText' variable value with 'someOtherText' variable value in someFile​

sed -e ':a' -e '$!{N;ba' -e "}; s|${someText}|${someOtherText}"

Rearrange blocks of text in lines​

Let's suppose that input contains some lines which match the pattern:

someText...(any characters)...twoDigits (any digits)

We want to rearrange these lines in the following way:

twoDigits-someText

Solution:

sed "s|^\(someText\)\(.*\)\([0-9]\{2\}\)$|\3-\1|g"

Explanation:

  • in a regular expression (left part), a line is represented in the following way:
    • '^' means the begginning of the line
    • \(someText\) - 'someText', represented as a group (the first one). We will need this group later, at the replacemet step
    • \(.*\) - any number ('*') of any characters ('.'), represented as another group (the second one)
    • \([0-9]\{2\}\) - any two ({2}) digits ([0-9]), represented as another group (the third one)
    • '$' means the end of the line
  • the replacement (right part) consists of:
    • the third group (two digits)
    • '-'
    • the first group (someText)

Use sub-shells in sed expressions​

Replace all current dd-mm-yyyy by yyyy-mm-dd:

sed "s|$(date +%d-%m-%Y)|$(date +%Y-%m-%d)|g"

We get and format current date using date command.

Delete a line from a file​

Delete line 5 from file /tmp/somefile:

sed -i '5d' /tmp/somefile