在bash中的特定列中剪切字符串 [英] cut string in a specific column in bash

查看:67
本文介绍了在bash中的特定列中剪切字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在第三个字段中切掉前导零,使其只有6个字符?

How can I cut the leading zeros in the third field so it will only be 6 characters?

 xxx,aaa,00000000cc
 rrr,ttt,0000000yhh

所需的输出

  xxx,aaa,0000cc
  rrr,ttt,000yhh

推荐答案

或者这是使用awk的解决方案

or here's a solution using awk

 echo " xxx,aaa,00000000cc
 rrr,ttt,0000000yhh"|awk -F, -v OFS=, '{sub(/^0000/, "", $3)}1'

输出

 xxx,aaa,0000cc
 rrr,ttt,000yhh

awk使用-F(或FS表示FieldSeparator),并且必须使用OFS表示OutputFieldSeparator).

awk uses -F (or FS for FieldSeparator) and you must use OFS for OutputFieldSeparator) .

sub(/srchtarget/, "replacmentstring", stringToFix)使用正则表达式在第三个字段($ 3)的(^)的开头查找4个0.

sub(/srchtarget/, "replacmentstring", stringToFix) is uses a regular expression to look for 4 0s at the front of (^) the third field ($3).

1print语句的简写.该脚本的简化版本为

The 1 is a shorthand for the print statement. A longhand version of the script would be

echo " xxx,aaa,00000000cc
 rrr,ttt,0000000yhh"|awk -F, -v OFS=, '{sub(/^0000/, "", $3);print}'
 # ---------------------------------------------------------^^^^^^

所有与awk的/pattern/{action}习惯用法有关.

Its all related to awk's /pattern/{action} idiom.

IHTH

这篇关于在bash中的特定列中剪切字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆