Chinaunix

标题: 求shell循环命令叠加方法 [打印本页]

作者: danielfancy    时间: 2014-03-19 15:51
标题: 求shell循环命令叠加方法
本帖最后由 danielfancy 于 2014-03-19 16:14 编辑

缘由:想实现一个shell先去mysql里面抓取一张list,然后存入变了,按里面的变量,让后生成拼接成一条可执行命令。
目前:有个TXT_LIST="a b c d…"
想输出拼接成这样的命令样例grep a txt | grep b | grep c | grep d | grep …

作者: reyleon    时间: 2014-03-19 15:59
http://bbs.chinaunix.net/thread-4118053-1-1.html

你是想干嘛?
作者: jason680    时间: 2014-03-19 16:00
回复 1# danielfancy

Don't do that, just tell us what you want?
   
作者: danielfancy    时间: 2014-03-19 16:05
不好意思,我重新描述了下,主要想随数组里面这项的变化,生成拼接一条可执行命令。
回复 2# reyleon


   
作者: jason680    时间: 2014-03-19 16:06
回复 4# danielfancy

why?
   
作者: danielfancy    时间: 2014-03-19 16:09
回复 3# jason680


    想 TXT_LIST="a b c d e",输出成 grep a txt | grep b | grep c | grep d | grep e这样
作者: danielfancy    时间: 2014-03-19 16:11
回复 5# jason680


    想实现一个shell先去mysql里面抓取一张list,然后存入变了,按里面的变量,让后生成拼接成一条可执行命令。
作者: zhaopingzi    时间: 2014-03-19 16:20
eval ???     
作者: seesea2517    时间: 2014-03-19 16:54
  1. [seesea@UC ~]$ echo $TXT_LIST | sed 's/ /| grep /g; s/^[^ ]*/grep & txt|/; s/|//;'
  2. grep a txt| grep b| grep c| grep d| grep e
复制代码
其实就是文本替换吧。
作者: reyleon    时间: 2014-03-19 16:54
回复 4# danielfancy


    看不懂你的需求.. {:3_194:}
作者: danielfancy    时间: 2014-03-19 17:26
回复 9# seesea2517


    当我TXT_LIST=“a b c d e”时候,生成 cat txt | grep a | grep b | grep c | grep d | grep e命令
    当我TXT_LIST=“a b c”时候,生成 cat txt | grep a | grep b | grep c 命令
作者: danielfancy    时间: 2014-03-19 17:27
回复 10# reyleon


    当我TXT_LIST=“a b c d e”时候,生成 cat txt | grep a | grep b | grep c | grep d | grep e命令
    当我TXT_LIST=“a b c”时候,生成 cat txt | grep a | grep b | grep c 命令
    当我TXT_LIST=“a b ”时候,生成 cat txt | grep a | grep b  命令
不知道这样能否实现?
作者: danielfancy    时间: 2014-03-19 17:52
回复 8# zhaopingzi


    eval看了下但没理解。。
作者: seesea2517    时间: 2014-03-19 18:02
回复 11# danielfancy


    不管是一楼还是六楼都没看到cat嘛,实现了就改需求了,楼主不是产品部吧,哈哈。
不难,楼主自己调整改改呗。
作者: zhaopingzi    时间: 2014-03-19 18:16
回复 13# danielfancy

转化成数组搞一吧,类似

  1. #/bin/bash
  2. bb=(a b c d e)
  3. k=${#bb[@]}
  4. x="cat txt|"
  5. for ((i=0;i<$k;i++))
  6. do
  7. x="$x |grep ${bb[i]}"
  8. done
  9. echo $x
复制代码

作者: yestreenstars    时间: 2014-03-19 21:14
回复 12# danielfancy

How about it?
  1. $ TXT_LIST="a b c d e"
  2. $ awk '{s="cat txt";for(i=0;i++<NF;)s=s" | grep "$i;print s}' <<< $TXT_LIST
  3. cat txt | grep a | grep b | grep c | grep d | grep e
  4. $ TXT_LIST="a b c"
  5. $ awk '{s="cat txt";for(i=0;i++<NF;)s=s" | grep "$i;print s}' <<< $TXT_LIST
  6. cat txt | grep a | grep b | grep c
  7. $ TXT_LIST="a b"
  8. $ awk '{s="cat txt";for(i=0;i++<NF;)s=s" | grep "$i;print s}' <<< $TXT_LIST
  9. cat txt | grep a | grep b
复制代码

作者: danielfancy    时间: 2014-03-20 09:23
回复 15# zhaopingzi


    感谢,昨天思维进死角了了,其实TXT_LIST=“a,b,c,d" 然后直接sed -e 和xargs 拼接起来称一行就好。
作者: danielfancy    时间: 2014-03-20 09:24
回复 16# yestreenstars


    学习,awk果然强大,感谢~




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2