【问题标题】:Getting error: sed: -e expression #1, char 2: unknown command: `.'出现错误:sed: -e expression #1, char 2: unknown command: `.'
【发布时间】:2013-06-05 03:18:28
【问题描述】:

编辑:已修复。现在关注优化代码。

我正在编写一个脚本来将一个文件中的数据分成多个文件。当我运行脚本时,我收到错误:“sed: -e expression #1, char 2: unknown command: `.'” 没有任何行号,这使得调试有点困难。我已经检查了我单独使用 sed 的行,它们可以正常工作。有任何想法吗?我意识到有很多事情我做了一些非常规的事情,并且有更快的方法来做一些事情(我确信有一种方法可以避免不断导入某个文件),但现在我只是想了解这一点错误。代码如下:

x1=$(sed -n '1p' < somefile | cut -f1)
y1=$(sed -n '1p' < somefile | cut -f2)
p='p'
for i in 1..$(seq 1 $(cat "somefile" | wc -l)) 
do
  x2=$(sed -n $i$p < somefile | cut -f1)
  y2=$(sed -n $i$p < somefile | cut -f1)
  if [ "$x1" = "$x2" ] && [ "$y1" = "$y2" ];
  then
    x1=$x2
    y1=$x2
  fi
  s="$(sed -n $i$p < somefile | cut -f3) $(sed -n $i$p < somefile | cut$
  echo $s >> "$x1-$y1.txt"
done

【问题讨论】:

    标签: bash shell sed


    【解决方案1】:

    问题出在下面一行:

    for i in 1..$(seq 1 $(cat "somefile" | wc -l)) 
    

    如果 somefile 有 3 行,那么这将导致以下值 i

    1..1
    2
    3
    

    显然,sed -n 1..1p &lt; filename 之类的内容会导致您观察到的错误:sed: -e expression #1, char 2: unknown command: '.'

    你宁愿:

    for i in $(seq 1 $(cat "somefile" | wc -l)) 
    

    【讨论】:

      【解决方案2】:

      这是问题的原因:

      for i in 1..$(seq 1 $(cat "somefile" | wc -l))
      

      试试吧

      for i in $(seq 1 $(wc -l < somefile))
      

      但是,您使用所有这些 sed 命令读取文件的次数太多太多了。只需阅读一次:

      read x1 y1 < <(sed 1q somefile)
      while read x2 y2 f3 f4; do
          if [[ $x1 = $x2 && $y1 = $y2 ]]; then
              x1=$x2
              y1=$x2
          fi
          echo "$f3 $f4"
      done < somefile > "$x1-$y1.txt"
      

      构造s 变量的行被截断——我假设每行有 4 个字段。

      注意:剪切和粘贴编码的一个问题是您会引入错误:您将 y2 分配给与 x2 相同的字段

      【讨论】:

      • 谢谢。非常感激。您的更正也应该会大大加快速度。
      • 现在它给了我:script2.sh:1:script2.sh:语法错误:重定向意外。知道这是为什么吗?
      • 另外,实际上我并没有剪切和粘贴。我只是忘记了我在看哪一个。感谢您指出这一点。我也没听懂。
      • Re: "redirection unexpected" -- 你用什么解释器来执行脚本? sh 还是 bash?提示:在stackoverflow中搜索字符串"redirection unexpected"
      • 我已经尝试将#!/bin/bash 添加到顶部,但当没有解决任何问题时,将其切换到#!/bin/sh。两者都弹出错误。
      猜你喜欢
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 2013-03-08
      • 2020-06-12
      • 2018-12-28
      • 2023-02-26
      • 1970-01-01
      相关资源
      最近更新 更多