2016-11-16 49 views
1

我只想檢查字符串,而不是整行。例如,我行是這樣只使用字符串檢查字符串

"pwd requisite dcredit=-5 ucredit=-1 lcredit=-1 ocredit=-1 minlen=14 difok=4 retry=2" 

我要檢查lcredit=-1此字符串

條件是:

  1. 如果這個字符串是相同這樣lcredit=-1我們跳過這個

  2. 如果字符串lcredit=2不在-1那麼這裏我們必須改變-1

  3. 如果字符串不是必須添加該行的字符串結尾。

和另外一個lcredit=-1包含該特定行中的任何位置。

如果我使用的是lineinfile它會改變整行並且行字符串位置不同。如果我使用replace,它只會被替換,但如果沒有,它不會添加。那麼任何其他的功能,以滿足我的條件?

+0

這似乎是您想要更改文件格式(如果可以的話)或寫入自定義分析器的情況;在Python中做這樣的事情很容易,在空白處分割,然後在等號上分割。 –

回答

1

一種方法是使用正則表達式(未經測試):

- name: If lcredit is specified, make sure it is -1 
    lineinfile: 
    regexp: "^pwd requisite(.*) lcredit=(-?\d+)(.*)" 
    backrefs: yes 
    line: 'pwd requisite\1 lcredit=-1\2' 
    dest: /etc/pam.d/whatever 

- name: If lcredit not specified, add it 
    lineinfile: 
    regexp: "^pwd requisite((?!.* lcredit=.*).*)" 
    backrefs: yes 
    line: 'pwd requisite\1 lcredit=-1' 
    dest: /etc/pam.d/whatever 

通常我會盡量避免正則表達式,尤其是複雜的問題,如上述。如果你還不知道他們,通常不會花錢去投資學習。所以我會做的是試圖尋找解決問題的方法。例如,它是否能夠始終指定整個確切的線條,而不是試圖巧妙地移動其各個部分?