Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash + sed/awk/cut to delete nth character

Tags:

bash

sed

awk

I trying to delete 6,7 and 8th character for each line.

Below is the file containing text format.

Actual output..

#cat test 
18:40:12,172.16.70.217,UP
18:42:15,172.16.70.218,DOWN

Expecting below, after formatting.

#cat test
18:40,172.16.70.217,UP
18:42,172.16.70.218,DOWN

Even I tried with below , no luck

#awk -F ":" '{print $1":"$2","$3}' test
18:40,12,172.16.70.217,UP

#sed 's/^\(.\{7\}\).\(.*\)/\1\2/' test  { Here I can remove only one character }
18:40:1,172.16.70.217,UP

Even with cut also failed

#cut -d ":" -f1,2,3 test
18:40:12,172.16.70.217,UP

Need to delete character in each line like 6th , 7th , 8th

Suggestion please

like image 586
user183980 Avatar asked Mar 14 '18 14:03

user183980


2 Answers

With GNU cut you can use the --complement switch to remove characters 6 to 8:

cut --complement -c6-8 file

Otherwise, you can just select the rest of the characters yourself:

cut -c1-5,9- file

i.e. characters 1 to 5, then 9 to the end of each line.

With awk you could use substrings:

awk '{ print substr($0, 1, 5) substr($0, 9) }' file

Or you could write a regular expression, but the result will be more complex.

For example, to remove the last three characters from the first comma-separated field:

awk -F, -v OFS=, '{ sub(/...$/, "", $1) } 1' file

Or, using sed with a capture group:

sed -E 's/(.{5}).{3}/\1/' file

Capture the first 5 characters and use them in the replacement, dropping the next 3.

like image 178
Tom Fenech Avatar answered Oct 10 '22 05:10

Tom Fenech


it's a structured text, why count the chars if you can describe them?

$ awk '{sub(":..,",",")}1' file

18:40,172.16.70.217,UP
18:42,172.16.70.218,DOWN

remove the seconds.

like image 35
karakfa Avatar answered Oct 10 '22 03:10

karakfa