简体   繁体   中英

How to extract first character from a string in Shell?

I have got a string (delimited by comma) from which I need to extract 'first character'

Eg  'A - one,B - two,C - three'

Expected output

A,B,C
echo 'A - one,B - two,C - three' | awk -F ',' '{OFS = ","} {for(i=1;i<=NF; i++) {$i=substr($i,1,1) }; print $0}'

For most cases, this should work (ascii)

echo 'A - one,B - two,C - three' | tr ',' '\n' | cut -b1

For character based selection (eg utf) this one is more suited

echo 'A - one,B - two,C - three' | tr ',' '\n' | cut -c1

sed解决方案:

echo 'A - one,B - two,C - three' | sed 's/\(.\)[^,]*,\{0,1\}/\1,/g;s/,$//'

This sed one-liner should work for your example:

sed -r 's/\s-[^,]*//g

Test:

kent$  sed -r 's/\s-[^,]*//g'<<< 'A - one,B - two,C - three' 
A,B,C

If you love to solve it with awk :

awk -F'\\s*-[^,]*' -v OFS="" '{$1=$1}7'

will work:

kent$   awk -F'\\s*-[^,]*' -v OFS="" '{$1=$1}7' <<<'A - one,B - two,C - three' 
A,B,C

I propose the following solution in "pure" bash:

X='A - one,B - two,C - three'

IFS=',' read -ra A <<< "$X"
RES=''
for W in "${A[@]}" ; do
   RES+=",${W:0:1}"
done

echo ${RES:1}
echo 'A - one,B - two,C - three'| awk '{print $1substr($3,4)substr($5,4)}'

A,B,C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM