sed stands for stream editor.
It is a filter program used for filtering and transforming text
It:
In the stream, it can:
It's part of the Gnu utility.
Sed is line-based therefore it is hard for it to grasp newlines and to manipulate eol characters.
Use the utility:
This expression capture and print the regular expression group
sed -n 's/.*\(your-group-expression\).*/\1/p'
This is:
Note the -n and p may not be necessary if the input is a single line.
Sed works by default on a line by line basis.
It's best to use an other tool better suited for the job.
Example:
cat foo.txt | tr -d '\n'
cat foo.txt | awk 'BEGIN{RS="\n";ORS="\\n"}1'
sed 'command1;...;commandN' inputFileName
sed -e 'command1' -e 'commandN' inputFileName
sed --expression='command1' inputFileName
sed -f myscript-with-commands.sed input.txt
sed --file=myscript-with-commands.sed input.txt
# In place editing - No outputFileName needed
sed -i 'command1;...;commandN' inputFileName
command syntax is
[LineAddressSelector]SingleLetterCommand[CommandOptions][sep]
where:
Using a script file avoids problems with shell escaping or substitutions.
Example script.sed: A sed file script with one command by line and a shebang
#!/bin/sed -f
sedCommand1
sedCommand...
sedCommandN
Run it:
sed -f script.sed inputFileName > outputFileName
chmod u+x subst.sed
script.sed inputFileName > outputFileName
A command is the first part in the sed expression command/regularExpression/modifier.
The Substitution command 2) replace a string
It's:
Syntax:
s/regexp/replacement/[flags]
# First occurence Default
sed 's/searchString/replacementString/' inputFileName > outputFileName
# All Occurences thanks to the g at the end
sed 's/searchString/replacementString/g' inputFileName > outputFileName
# In place editing - No outputFileName needed
sed -i 's/searchString/replacementString/g' inputFileName
# to use backslash characters. tab by arrow and end of line by reverse p
sed 's/\t/→/g;s/$/¶'
where: in the expression 's/searchString/replacementString/':
The -n delete the output that is not matched
# prints only line 45
sed -n '45p' file.txt
# prints the first line of the first file (one.txt) and the last line of the last file (three.txt)
# Use -s to reverse this behavior.
sed -n '1p ; $p' one.txt two.txt three.txt
# Print line that matches an expression
sed -n "/patternExpression/p" one.txt
The d (delete) command delete lines (to delete a word, substitute it with nothing)
# line
'/regularExpression/d'
# deletes lines 30 to 35
'30,35d'
Example:
sed '/^ *$/d' inputFileName
s/yourword//g
Search for line that starts with foo and quit with the 42 exit code
/^foo/q42
https://www.gnu.org/software/sed/manual/sed.html#sed-commands-list
sed -n "/patternExpression/p" targetFilePath
where p means print
Flow of control can be managed by:
An instruction b followed by a valid label name will move processing to the block following that label.