[英]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) 在大多数情况下,这应该可以工作(ascii)
echo 'A - one,B - two,C - three' | tr ',' '\n' | cut -b1
For character based selection (eg utf) this one is more suited 对于基于字符的选择(例如utf),此选项更适合
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单线应适用于您的示例:
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解决它:
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: 我在“纯” 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.