检查文件中某一行特定索引范围内是否有space,将space替换为0

Check if there is space in specific range of indexes in a line in a file and replace the space with 0

我遇到了以下问题。我在一个文件中有几行,下面显示了一个示例。 位置 4-10 之间的值可以包含值和 spaces 的任意组合,并且仅当它为空 space.

时才用 0 替换
#input.txt

014       789000
234455    899800    
1213839489404040

在上面的示例行中,我们可以看到位置 4-10 之间有空 spaces。这个要检查的位置是固定的。我希望能够检查文件中的每一行在位置 4-10 之间是否有空 spaces,如果有空 space,我希望能够用 0 替换它。我在文件中提供了所需的输出。

#desired output in the input.txt

0140000000789000    # note that 0 has been added in the position 4-10
2344550000899800    # # note that 0 has been added in the position 7-10
1213839489404040

我能够在下面的代码中执行以下操作。下面的代码只能使用 sed 命令在指定位置添加值,我希望能够修改这段代码,使其能够完成上述任务。

有人可以帮助我吗?

我的代码:

#append script
function append_vals_to_line {
    insert_pos=$(( - 1))
    sed -i 's/\(.\{'$insert_pos'\}\)/''/' ""
}

column_num_to_insert=""
append_value =""
input_file_to_append_vals_in =""

append_vals_to_line "$column_num_to_insert" "$append_value" "$input_file_to_append_vals_in"

我建议 awk 解决方案:

awk '{s = substr([=10=], 4, 7); gsub(/ /, 0, s); print substr([=10=], 1, 3) s substr([=10=], 11)}' file

#input.txt

0140000000789000
2344550000899800
1213839489404040

更具可读性的版本:

awk '{
   s = substr([=11=], 4, 7)
   gsub(/ /, 0, s)
   print substr([=11=], 1, 3) s substr([=11=], 11)
}' file

该命令首先获取变量s中第4到第10个位置的子字符串。然后使用 gsub 我们用 0 替换每个 space 最后我们重新组合并打印整行。


考虑这个 awk 从参数获取开始和结束位置的命令:

awk -v p1=4 -v p2=10 '{
   s = substr([=12=], p1, p2-p1+1)
   gsub(/ /, 0, s)
   print substr([=12=], 1, p1-1) s substr([=12=], p2+1)
}' file

你可以这样做:

awk '
/[[:blank:]]/{
    sub(/[[:blank:]]*$/,"")   # remove trailing spaces if any
    gsub(/[[:blank:]]/,"0")   # replace each /[[:blank:]]/ with "0"
} 1' file

或者,您可以这样做:

awk '
length() {
    [=11=]=sprintf("%s%0*d",,16-length(),)
} 1' file   

要么打印:

0140000000789000
2344550000899800
1213839489404040