Reputation: 51
Input strings are as follows.
6.5.1.2.3
6.10.3.9.6
7.2.0.0.0
10.11.12.13.4
And I want to extract first two digit and replace period character to underscore using sed
6_5
6_10
7_2
10_11
When I used this:
sed 's/\./_/g' | cut -c 1-3
6_10, 10_11 result was not correct.
Is there any work around here?
Upvotes: 0
Views: 101
Reputation: 289495
awk
is also useful for such things. If you set the output field separator OFS
:
$ awk -F"." -v OFS="_" '{print $1, $2}' file
6_5
6_10
7_2
10_11
But if you really need sed
use back references (here with extended regular expressions — note that the option is sometimes -E
and sometimes only basic regular expressions are supported by sed
):
$ sed -r 's/([0-9]+)\.([0-9]+).*/\1_\2/' file
6_5
6_10
7_2
10_11
If you want to perform in-place replacing, you can either say awk/sed '...' file > tmp_file && mv tmp_file file
or, use sed -i
(on those platforms where it is supported, but note that there are differences between GNU sed
and BSD (macOS) sed
), or gawk -i inplace
(GNU Awk).
Note in both cases I am using a single command instead of piping to another one.
Upvotes: 4
Reputation: 322
My awk
solution would be :
$ echo "6.5.1.2.3
> 6.10.3.9.6
> 7.2.0.0.0
> 10.11.12.13.4" | awk 'BEGIN{FS=".";OFS="_"}{print $1,$2}'
6_5
6_10
7_2
10_11
Upvotes: 0
Reputation: 15603
The input is so simple it can be done easily with just cut
and tr
. Use cut
to pick out the first two fields (delimited by .
), and then use tr
to change the dot to an underscore:
$ cut -d '.' -f 1,2 input | tr '.' '_'
6_5
6_10
7_2
10_11
Upvotes: 1
Reputation: 17643
You are almost there:
echo 1.2.3.4 | sed 's/\./_/g' | cut -d "_" -f1,2
(Escaped the dot with \
, and specified the delimiter for cut
.)
Upvotes: 1