Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 切割后为变量赋值?_Linux - Fatal编程技术网

Linux 切割后为变量赋值?

Linux 切割后为变量赋值?,linux,Linux,作为Unix新手,我希望解析文件的完整路径 /Users/E/atsp_0001.tar.gz 进入0001并将0001分配给变量sub\u id 虽然解析可能很笨拙,但其工作原理如下: E$ file=/Users/E/atsp_0001.tar.gz E$ echo ${file##*/} | cut -d "_" -f2 | cut -d "." -f1 0001 E$ file=/Users/E/atsp_0001.tar.gz E$ sub_id=${file##*/} | cut

作为Unix新手,我希望解析文件的完整路径

/Users/E/atsp_0001.tar.gz

进入
0001
并将
0001
分配给变量
sub\u id

虽然解析可能很笨拙,但其工作原理如下:

E$ file=/Users/E/atsp_0001.tar.gz
E$ echo ${file##*/} | cut -d "_" -f2 | cut -d "." -f1
0001
E$ file=/Users/E/atsp_0001.tar.gz
E$ sub_id=${file##*/} | cut -d "_" -f2 | cut -d "." -f1
E$ echo ${sub_id}

E$
然后,我未能将
0001
分配给如下变量:

E$ file=/Users/E/atsp_0001.tar.gz
E$ echo ${file##*/} | cut -d "_" -f2 | cut -d "." -f1
0001
E$ file=/Users/E/atsp_0001.tar.gz
E$ sub_id=${file##*/} | cut -d "_" -f2 | cut -d "." -f1
E$ echo ${sub_id}

E$
如果有人可以的话,我将不胜感激
(1) 解释这不起作用的原因以及如何修复它,以及(2)改进笨拙的解析。

我们就是这样做的。您可以使用
$()
。您也可以使用``而不是
$()
,但我不推荐使用它

:~> file=/Users/E/atsp_0001.tar.gz
:~> echo ${file##*/} | cut -d "_" -f2 | cut -d "." -f1
0001
:~> variabletest=$(echo ${file##*/} | cut -d "_" -f2 | cut -d "." -f1)
:~> echo $variabletest
0001
您在变量赋值中执行多个操作,而不是存储值,这就是它不适合您的原因

echo
将打印数据,但您正在执行管道操作,因此在将数据封装起来以将其标记为单个操作之前,该操作无法工作。您的解析是正常的,因为它取决于您的文件命名约定。但我会使用base name命令

:~> echo $file
/Users/E/atsp_0001.tar.gz

:~> basename $file
atsp_0001.tar.gz
这将使道路变得平坦

因此,您可以执行
variabletest=$(echo basename$file | cut-d“”-f2 | cut-d“.”-f1)

非常感谢!(1) 因此,
echo
并不意味着
print
,是吗?(2) 解析不是很笨拙吗?