【问题标题】:Extract substrings with certain length randomly from a file with Bash使用 Bash 从文件中随机提取一定长度的子字符串
【发布时间】:2017-08-20 15:43:01
【问题描述】:

我有多个文本文件,我需要从每个文件中提取具有一定长度的随机连续子字符串。

例如,我需要提取 5 个随机子串,每个子串包含 3 个连续字符,或者 4 个随机子串,每个子串包含 20 个字符。

实际上,我们假设这是其中一个文件的内容

Welcome to stackoverflow the best technical resource ever

所以如果我想要五个随机子字符串,每个子字符串由 3 个字符组成,我希望输出如下所示:

elc
sta
tec
res
rce

非常感谢您的帮助。

【问题讨论】:

  • 如果最长的单词比这短,你打算如何获得 20 个连续的字符?您是否连接单词以消除空格?
  • 我不关心某些单词,空格对我来说是可以接受的字符。
  • 例如,如果我想要 10 个随机字符,那么这些是可以接受的:“Welcome to” “stackoverf” “best tech”

标签: bash random substring


【解决方案1】:

awk 来救援!

awk -v n=5 -v s=3  'BEGIN {srand()}
                          {len=length($0); 
                           for(i=1;i<=n;i++) 
                              {k=rand()*(len-s)+1; printf "%s\t", substr($0,k,s)}
                               print ""}' file

提取的子串中可能有空格

【讨论】:

  • 我收到这个错误:./script.sh: line 3: syntax error near unexpected token (' ./script.sh: line 3: awk -vn=5 -vs=3 ''BEGIN {srand()}'跨度>
  • BEGIN前面有两个单引号,应该只有一个。
【解决方案2】:

创建一个函数来选择一个随机子字符串:

random_string() {
  line=$1
  length=$2
  # make sure we start at a random position that guarantees a substring of given length
  start=$((RANDOM % ((${#line} - $length))))
  # use Bash brace expansion to extract substring
  printf '%s' "${line:$start:$length}"
}

循环使用函数:

#!/bin/bash

while IFS= read -r line; do
  random1=$(random_string "$line" 3)
  random2=$(random_string "$line" 20)
  printf 'random1=[%s], random2=[%s]\n' "$random1" "$random2"
done < file

file 中包含内容Welcome to stackoverflow the best technical resource ever 的示例输出:

random1=[hni], random2=[low the best technic]
random1=[sta], random2=[e best technical res]
random1=[ove], random2=[ackoverflow the best]
random1=[rfl], random2=[echnical resource ev]
random1=[ech], random2=[est technical resour]
random1=[cal], random2=[ome to stackoverflow]
random1=[tec], random2=[o stackoverflow the ]
random1=[l r], random2=[come to stackoverflo]
random1=[erf], random2=[ stackoverflow the b]
random1=[me ], random2=[ the best technical ]
random1=[est], random2=[ckoverflow the best ]
random1=[tac], random2=[tackoverflow the bes]
random1=[e t], random2=[o stackoverflow the ]
random1=[al ], random2=[come to stackoverflo]

【讨论】:

  • 非常感谢,效果很好,但有一个问题,许多末尾有空格的字符串都被删除了!
  • IFS=read -r 中丢失。添加了这一点,这将解决尾随空格问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 2023-03-17
  • 1970-01-01
  • 2021-03-15
相关资源
最近更新 更多