文件名的 awk/sed 部分

Jas*_*son 3 command-line sed awk filenames

每当我将文件名作为参数放入命令行时,我只想 awk/sed 文件名的前缀。

例如,

我有多个文件:

a.fastq.gz
b.fastq.gz
c.fastq.gz
d.fastq.gz
Run Code Online (Sandbox Code Playgroud)

如果我执行:

sh test.sh --INFILE b.fastq.gz
Run Code Online (Sandbox Code Playgroud)

我想要的输出是:

b
Run Code Online (Sandbox Code Playgroud)

我尝试过但失败的是,

prefix="sed 's/.fastq//' ${INFILE}"
Run Code Online (Sandbox Code Playgroud)

jes*_*e_b 8

Using shell parameter expansion (assuming you are assigning your filename to INFILE):

INFILE=b.fastq.gz
prefix=${INFILE%%.*}
Run Code Online (Sandbox Code Playgroud)

Or if your suffix is sure to be fixed and you want to be more precise (always recommended when possible):

prefix=${INFILE%.fastq.gz}
Run Code Online (Sandbox Code Playgroud)

${parameter%word}

${parameter%%word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

  • @Jason 如果您不在标准的 Unix shell 环境中工作,那么您最好让我们知道您在做什么。我们假设您正在使用命令行或编写 shell 脚本。 (2认同)

Kus*_*nda 7

使用标准basename实用程序删除已知后缀:

$ basename b.fastq.gz .fastq.gz
b
Run Code Online (Sandbox Code Playgroud)

With a variable:

$ pathname="/some/path/name.fastq.gz"
$ basename "$pathname" .fastq.gz
name
Run Code Online (Sandbox Code Playgroud)

Assigning to a variable:

$ prefix=$( basename "$pathname" .fastq.gz )
$ printf 'Prefix is "%s"\n' "$prefix"
Prefix is "name"
Run Code Online (Sandbox Code Playgroud)

In a loop (over all the .fastq.gz files in the current directory):

for filename in ./*.fastq.gz; do
    prefix=$( basename "$filename" .fastq.gz )
    # Do things using "$prefix" here
done
Run Code Online (Sandbox Code Playgroud)

  • @ParanoidGeek 我不会进行更改以支持非 POSIX shell。这适用于任何当前的 `/bin/sh` 实现(除非我特别提到,否则我所有的答案都是如此)。另请参阅 [不推荐使用 \*sh shells 中的反引号(即 \`cmd\`)?](//unix.stackexchange.com/q/126927) (2认同)