5

I need to extract the characters before last colon : and also remove the square brackets [] in the last line. My file structure is

256.XXX.XXX.X:20234
214.XXX.XXX.X:7249
[2200:XXXX:XXXX:XXX:XXXX:XXXX:XXXX:XXXX]:46288

I need output file as in the form of:

256.XXX.XXX.X
214.XXX.XXX.X
2200:XXXX:XXXX:XXX:XXXX:XXXX:XXXX:XXXX
ilkkachu
  • 138,973
Nani
  • 353

5 Answers5

10

Remove everything after the last colon, and then any brackets left anywhere:

sed 's/:[^:]*$//; s/[][]//g'

Or

sed 's/\(.*\):.*/\1/; s/[][]//g'

(here using the fact that the first .* will be greedy and swallow as many :s as possible).

ilkkachu
  • 138,973
3

This will extract all characters before last 'colon' and remove the brackets [ ] as the example you give.

rev <yourfile.txt | cut -d: -f2- | rev | tr -d '[]'

Replace yourfile.txt by your file name or remove the word <yourfile.txt to read the standard output.

2

awk -F: '{OFS=":"; NF--; print $0}' $file

or

cat file | awk -F: '{OFS=":"; NF--; print $0}'

which breaks down as:

  • -F: set the input field separator to :
  • OFS=":" set the output field separator to :
  • NF-- reduce the Number of Fields by 1 (get rid of the last field)
  • print $0 print the remaining records, separated by the OFS (:) character.

Update to also remove the square brackets:

awk -F: '{OFS=":"; NF--; gsub(/\[|\]/, ""); print $0}' $file

  • added gsub(/\[|\]/, "")1 which performs a global substitution on the square brackets, replacing them with nothing, and returning the substituted string.
Tim Kennedy
  • 19,697
2

Shell only:

while IFS= read -r line; do
    tmp=${line%:*}               # remove last colon and following chars
    tmp=${tmp#"["}               # remove leading open bracket
    result=${tmp%"]"}            # remove trailing close bracket
    printf "%s\n" "$result"
done < file
glenn jackman
  • 85,964
0

Command:

awk -F ":" 'OFS=":"{$NF="";print $0}' filename | sed "s/:$//g"| sed "s/^\[//g"|sed "s/\]//g"

output

256.XXX.XXX.X
214.XXX.XXX.X
2200:XXXX:XXXX:XXX:XXXX:XXXX:XXXX:XXXX
  • 1
    This doesn’t seem any better than Tim Kennedy’s existing answer. For future reference, if you’re using AWK, you don’t need sed too... – Stephen Kitt May 15 '19 at 16:38