1

I want to format text using awk or sed. I have text looking like,

H1 (dxfault)
H337 (Unxr)
H1106 (hast)
H1129 (h1129)
H1370 (hlan1370)

I want to remove the letter H and everything after the first space, and format numbers look like 1,337,1106,1129,1370

I found two different sed options

First:

sed 'y/H/ /' #for removing H letter in front 

Second:

sed 's/\s.*$//' #for removing everything after first break "space" 

How can I combine these commands and add a comma after the numbers?

3

You can use sed to get the numbers only and paste to merge the lines with , as delimiter:

sed -E 's/^H([0-9]*).*$/\1/' file | paste -sd,

or grep and paste:

grep -Po '^H\K[0-9]*' file | paste -sd,
grep -o '^H[0-9]*' file |  cut -c 2- | paste -sd,

You can exchange the linebreak with , with sed, but imo paste is easier.

  • hi.. can you tell me why can't we use or(|) operator sed -E 's/^H|\s.*$/\1/' also what does \1 and () mean? – Goron Apr 11 at 8:04
  • You can't use |, because you want to match ^H at the beginning and \s.*$ at the end of the line which are two matches (not one or the other). () is used to group the matches and \1 is a backreference to the first group in the replacement. See for example sed -E 's/(^H)(.*)(\s.*$)/1:\1 2:\2 3:\3/' file which uses 3 groups and backreferences. – Freddy Apr 11 at 8:49
0

Or sed/grep using tr:

$ sed -E 's/H([0-9]+).*/\1/' file | tr '\n' ,

$ grep -o '[0-9]\+\s' file | tr -s '\n ' ,
  • tr '\n' , replaces newline with comma
  • tr -s '\n ' , replaces newline and space with one comma
0

I have done by below method

sed -e "s/H//g" -e "s/\s.*//g" filename | perl -pne "s/\n/,/g"| sed "s/,$//g"

output

1,337,1106,1129,1370
0

Tried with Python too

import subprocess
import re
k=re.compile(r'\s.*')
u=[]
f=[]
l=open('l.txt','r')
for i in l:
    u.append(re.sub("H","",i).strip())
for m in u:
    f.append(re.sub(k,"",m))

print ",".join(f)

output

1,337,1106,1129,1370
0

Using sed, assuming that any characters may be used but there is only 1 space ....

sed -E "s/^H(.+) .*$/\1/g" filename | paste -sd,

I would rather opt for grep though which allows for any characters and extracts the match until the first space found

grep -Po "(?<=^H)[^ ]*" filename | paste -sd,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.