4

I am learning sed, so please bear with me. I am trying to use sed to find all files containing "install" in a log and output to a new file. Here's an example of the file being searched:

2016-05-04 07:38:46 install libcairomm
2016-05-05 07:38:47 status half-installed libcairomm
2016-05-05 07:39:49 status unpacked libcairomm

So, it would output the first line only. Here is what I have been trying with some other variations as well:

sed -n '/[0-9]{2} install/p' > new.txt

All the variations of this I have tried have not done anything. It creates an empty file.

Any help would be appreciated :)

codeforester
  • 39,467
  • 16
  • 112
  • 140
rrfeva
  • 77
  • 1
  • 5
  • Possible duplicate of [sed find and replace with curly braces](https://stackoverflow.com/questions/9205669/sed-find-and-replace-with-curly-braces) – jww Feb 18 '18 at 01:06
  • Maybe awk would make more sense? https://stackoverflow.com/questions/13077631/is-it-possible-to-print-different-lines-to-different-output-files-using-awk – dstromberg Feb 18 '18 at 01:39

2 Answers2

2

Using sed

Observe that the following returns nothing:

$ sed -n '/[0-9]{2} install/p' file

But, this works:

$ sed -n '/[0-9]\{2\} install/p' file
2016-05-04 07:38:46 install libcairomm

The issue is that, in sed's default basic regular expressions, { and } are treated as ordinary characters. To make them special, they must be escaped with a backslash.

Alternatively, one can specify -E so that sed uses the more modern Extended Regular Expressions:

$ sed -En '/[0-9]{2} install/p' file
2016-05-04 07:38:46 install libcairomm

Saving to file

To save the output in a file, instead of displaying it in the terminal, add back the redirection > new.txt:

sed -n '/[0-9]\{2\} install/p' file > new.txt

Or:

sed -En '/[0-9]{2} install/p' file > new.txt

Compatibility

On very old versions of GNU sed, one cannot use -E. One must use -r instead:

sed -rn '/[0-9]{2} install/p' file > new.txt

Using grep

This task does not require sed's many advanced features. grep is sufficient:

$ grep -E '[0-9]{2} install' file
2016-05-04 07:38:46 install libcairomm

Or:

grep -E '[0-9]{2} install' file >new.txt
John1024
  • 109,961
  • 14
  • 137
  • 171
0

Your command, sed -n '/[0-9]{2} install/p' > new.txt is using Basic RegEx or BRE. The GNU Sed manual explains the difference between BRE and Extended RE or ERE.

To solve your issue, use ERE with the -E or -r flags:

sed -rn '/[0-9]{2} install/p' > new.txt

Or, use backslashes to escape the curly braces in BRE:

sed -n '/[0-9]\{2\} install/p' > new.txt
codeforester
  • 39,467
  • 16
  • 112
  • 140
Guy
  • 637
  • 7
  • 15