I have the following file foo.txt:
1
AbcdJ
8192
Pak78
8291
I would like a bash script that extracts all the lines containing only integers (e.g. 1, 8192 but not AbcdJ or Pak78) and outputs it to bar.txt.
I have the following file foo.txt:
1
AbcdJ
8192
Pak78
8291
I would like a bash script that extracts all the lines containing only integers (e.g. 1, 8192 but not AbcdJ or Pak78) and outputs it to bar.txt.
This extracts lines that contain only digits:
This sends the output to
bar.txt
:How it works
When you want to select lines from a file,
grep
is first utility to try.^[[:digit:]]+$
is a regular expression. In it,^
matches the beginning of a line,[[:digit:]]+
matches one or more digits, and$
matches the end of a line. Because this regex starts with^
and ends with$
, it only matches whole lines. An alternative way of matching only whole lines is to use the-x
option:The option
-E
tellsgrep
to use extended regular expressions. This reduces the need to escape things in the regex.The
>
signifies redirection. It causes the output that would have appeared on the screen to go to a file namedbar.txt
.AWK solution:
Use
>
to redirect output to fileSome other tools:
sed
:bash
, slower than other approaches:To save the output on another file, use output redirection,
>
: