在 linux 中使用“sed"时出现额外字符错误 [英] Extra characters error when using 'sed' in linux

查看:71
本文介绍了在 linux 中使用“sed"时出现额外字符错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课程涉及编写一个 linux 脚本来从伪垃圾文件夹中恢复"文件.我已经这样做了,看起来它应该工作,但它没有.相反,我收到一条错误消息:

My coursework involves writing a linux script to 'restore' files from a pseudo trash folder. I've done this, and it looks like it should work, but it doesn't. Instead, I get an error that says:

sed: -e 表达式 #1, char 2: 命令后的额外字符

sed: -e expression #1, char 2: extra characters after command

但我不明白为什么,因为我没有在代码中的任何地方使用 -e 表达式.然而,我的大脑因为长时间盯着代码而感到疲倦,以至于它可能只是一个我看不到的愚蠢错误.任何帮助将不胜感激!

but I can't see why, since I don't use the -e expression anywhere in my code. However, my brain's fried from staring at code for so long that it might just be a silly mistake that I can't see. Any help would be appreciated greatly!

这是我的代码:

#!/bin/sh

if [ "$1" = "-n" ]
then

##if command is used with -n, prompts user to enter a new location for the file

  cd ~/my-documents/mydir01/trashbin
  restore=`sed "$2" ~/my-documents/mydir01/locations`
  name=`basename "$restore"`

  echo $name
  echo "Enter new location for this file."
  read loc
  echo $loc
  mv -i `"$name" "$newloc"/"$name"`

else

##file will be restored to its previous location

  cd ~/my-documents/mydir01/trashbin
  restore=`sed "$1" ~/my-documents/mydir01/locations`
  loc=`dirname "$restore"`
  echo $loc
  name=`dirname "$restore"`
  mv $1 $name
fi

推荐答案

你究竟是如何调用你的 shell 脚本的?$1 和 $2 的值是由 sed 使用的,看起来这可能是出现问题的地方.

How exactly are you invoking your shell script? The values of $1 and $2 are used by sed, and it looks like that might be where the problem is occurring.

根据原始海报的评论,似乎期望的最终目标是将原始文件的位置存储在 ~/my-documents/mydir01/locations 中,然后在文件需要时从那里检索它被恢复.

Based on the comments from the original poster, it appears that the desired end goal is to store the location of the original file in ~/my-documents/mydir01/locations, and later retrieve it from there when the file needs to be restored.

一种方法是使用元组(例如键值对)来存储和检索此信息.例如,如果原始文件名是 X,新文件名是 Y,则在更改时,您需要在位置文件中添加X Y".稍后,当您想要恢复文件时,您可以使用 X(或者可能是 Y)从位置文件中选择这一行(提示:使用 grep),然后使用 awk 或 perl(例如:awk '{print $1}') 选择该行的第一部分.这样做会为您提供 X,这正是您想要的,因为 X 是文件的原始名称.

One way to do this would be by using a tuple (such as a key-value pair) to store and retrieve this information. For instance, if the original file name is X and the new file name is Y, at the time of the change, you would add "X Y" to the locations file. Later, when you want to restore the file, you would use either X (or perhaps Y) to pick this line from the location file (hint: use grep), and then use awk or perl (example: awk '{print $1}') to pick the first part of the line. Doing this gives you X, which is what you want, since X is the original name of the file.

总而言之,这个问题根本与 sed 无关.

In summary, this question is really not about sed at all.

祝你好运.

这篇关于在 linux 中使用“sed"时出现额外字符错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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