如何计算字符串第一行的字符数?

时间:2018-01-16 19:30:46

标签: bash

我知道如何计算bash中字符串的长度:

var1=$'Title\n\nsome text some text some text some text'
echo "$var1"
length=${#var1}
echo "Length: $length"

我也知道如何计算文件的EACH行中的数字字符:

awk '{ print length($0); }' file

但它不适用于bash变量,仅适用于文件:

awk: fatal: cannot open file `var1' for reading (No such file or directory)

但我想计算第1行和第3行(或特定行)中的字符数。不是所有这些的长度,因为字符串可能很长。有可能吗?

var1=$'Title\n\nsome text some text some text some text'
echo "$var1"
length_of_1st_line=[???]
length_of_3rd_line=[???]
echo "$length_of_1st_line"
echo "$length_of_3rd_line"

如何计算bash中字符串变量的第一行(或第三行或任何其他给定行)的字符数并将其保存在变量中?

5 个答案:

答案 0 :(得分:2)

echo -e "$var1" | awk 'NR==1 || NR==3 { print length($0); }'

输出:

5
39

答案 1 :(得分:0)

您可以awk使用字符串作为cheating的输入:

$> var1='Title\n\nsome text some text some text some text'
$> awk '{print length($0)}' <(echo -e $var1)
5
0
39

答案 2 :(得分:0)

嗯,正确引用(:

$ awk "BEGIN{print \"$(head -1 <(echo "$var1"))\"}"
Title

length

$ awk "BEGIN{print length(\"$(head -1 <(echo "$var1"))\")}"
5

答案 3 :(得分:0)

  

如何计算bash中字符串变量的第一行(或第三行或任何其他给定行)的字符数并将其保存在变量中?

示例1:(1)将输入行存储在字符串而不是文件中; (2)使用sed提取给定字符串的给定行然后计算该行的长度的函数; (3)将结果存储在数组_len

#!/bin/bash

# lines are stored in a string, not in a file

_string='title
this is the second line
the third line is like this
and this is the forth line, a bit longer
this one shorter'

# function to print length of line $1 of string $2

_lenln() {
  local s=$(sed -n "$1{p;q}" <<<"$2")
  echo ${#s}
}

# test that function, store results in an array _len

_len=()

_len[1]=`_lenln 1 "$_string"`
_len[2]=`_lenln 2 "$_string"`
_len[4]=`_lenln 4 "$_string"`

echo ${_len[1]}
echo ${_len[2]}
echo ${_len[4]}

示例2:(1)将输入行存储在字符串中而不是文件中; (2)awk计算第1行和第3行的长度; (3)将结果存储在数组_len

#!/bin/bash

_string='title
this is the second line
the third line is like this
and this is the forth line, a bit longer
this one shorter'

_len=()

# awk to contruct bash command that calulate length of line 1 and 3
# then store those results in an array _len

eval $(awk 'NR==1||NR==3{print "_len[" NR "]=" length($0)}' <<<"$_string")

echo ${_len[1]}
echo ${_len[3]}

答案 4 :(得分:0)

没有必要为bash(如awk)使用外部任何东西。

$ var1=$'Title\n\nsome text some text some text some text'
$ n=0; while read x; do a[$((++n))]=${#x}; done <<<"$var1"

这将使用键/值对填充数组$a,其中键是行号,值是该行上的字符数。循环使用herestring读取输入。

从这一点来说,您有多个选项可以访问数组的内容:

$ declare -p a
declare -a a=([1]="5" [2]="0" [3]="39")
$ for (( n=1; n<=${#a[@]}; n++ )); do printf '%d: %d\n' "$n" "${a[$n]}"; done
1: 5
2: 0
3: 39
$ echo "${a[3]}"
39

您可能需要考虑使用read -r,具体取决于您的输入。