Suppose I have 6 lines of text.
Series
Of
Word
73914
Again
Word
I need to prepend a string to the beginning of lines that contain ONLY numbers. Say I insert number-
Series
Of
Word
number-73914
Again
Word
Currently I run two commands to achieve the desired result. I wonder if there is a more efficient method.
Note: There are 1000+ lines, so preferably this applies to all lines ( I already state it ).
sed
can do that:In case we want to account for empty lines, we'd use
+
and-r
option:Once you verify everything is proper, you can use
-i
option to edit the file itself, i.e.sed -i ...
. Otherwise, you can always make a copy of the file withsed 's/^[[:digit:]]*$/number-&/' input.txt > output.txt
Note that this assumes consistent file format, with no leading whitespaces or trailing whitespaces on each line.
And here's Python as extra:
One way using awk:
It's unclear whether you mean numbers or just 0-9. Here's a Perl one-liner that picks out the likes of 123, 3.14 and 1e-12 while ignoring various representations of infinity and not-a-number:
I changed the prefix to "N:" simply because "number--1" looks a bit rubbish. Note that this treats " 1", for example, as not numeric. If that is undesirable behaviour, do not include the "m/^\s/" test for leading whitespace.
If you mean "0-9", Sergiy's sed solution above is fine.
You can try this